package com.nineclock.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.service.SmsService;
import com.nineclock.system.service.SysUserService;
import com.nineclock.common.enums.ResponseEnum;

import com.nineclock.system.dto.SysRegisterDTO;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Package: com.nineclock.system.service.impl
 * @ClassName: SysUserServiceImpl
 * @Author: 小康
 * @CreateTime: 2021-06-11 16:54
 * @Description:
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    SysUserMapper userMapper;

    @Autowired
    SmsService smsService;

    /**
     * 1. 健壮性判断
     * 2. 校验验证码
     * 3. 注册用户
     *
     * @param sysRegisterDTO
     * @return
     */
    @Override
    public Long regiester(SysRegisterDTO sysRegisterDTO) {
        if(sysRegisterDTO == null || sysRegisterDTO.getMobile() == null || sysRegisterDTO.getCheckcode() == null || sysRegisterDTO.getPassword() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //调用的 短信验证的接口 校验验证码
        Boolean flag = smsService.verify(
                sysRegisterDTO.getMobile(), SMSConstant.SMS_TYPE_REGISTER, sysRegisterDTO.getCheckcode());
        if(!flag){
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }
        //创建用户
        SysUser user = new SysUser();
        //保存加密后的密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(sysRegisterDTO.getPassword()));
        user.setCreateTime(new Date());
        user.setMobile(sysRegisterDTO.getMobile());
        user.setStatus((short)1);

        userMapper.insert(user);

        return user.getId();
    }
    @Override
    public SysUserDTO queryUser(String username) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<SysUser>();
        queryWrapper.eq(SysUser::getStatus,1);
        queryWrapper.eq(SysUser::getUsername,username).or().eq(SysUser::getMobile,username);

        SysUser sysUser = userMapper.selectOne(queryWrapper);
        if(sysUser != null){
            SysUserDTO sysUserDTO = BeanHelper.copyProperties(sysUser, SysUserDTO.class);
            return sysUserDTO;
        }

        return null;

    }
}
